package com.tcm.ucenter.service;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.pager.PageBean;
import com.base.core.pager.PageContext;
import com.base.core.utils.R;
import com.base.genid.generator.UidGenerator;
import com.base.core.dozer.DozerConvert;
import com.tcm.ucenter.domain.dto.UserAddressDTO;
import com.tcm.ucenter.domain.entity.UserAddress;
import com.tcm.ucenter.domain.enums.BusinessCodeEnum;
import com.tcm.ucenter.mapper.UserAddressMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@DubboService(version = "0.0.1-alpha")
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @DubboReference(version = "0.0.1-beta", group = "cached-uid", check = false, retries = 3)
    private UidGenerator uidGenerator;

    /**
     * 获得单条地址信息
     *
     * @param id
     * @return
     */
    @Override
    public UserAddressDTO findById(Long id) {
        UserAddress userAddress = userAddressMapper.findById(id);
        UserAddressDTO userAddressVo = null;
        if (ObjectUtil.isNotNull(userAddress)) {
            userAddressVo = DozerConvert.copyProperties(userAddress, UserAddressDTO.class);
        }
        return userAddressVo;
    }

    /**
     * 通过userId分页查询地址
     *
     * @param userId
     * @param start
     * @param pagesize
     * @return
     * @throws ServiceException
     */
    @Override
    public PageBean<UserAddressDTO> listPageByUserId(Long userId, Long start, Long pagesize) throws ServiceException {
        Long count = userAddressMapper.countByUserId(userId);
        PageContext.setCurrentPage(start);
        PageContext.setPageSize(pagesize);
        PageContext.setDataCount(count);
        if (count.intValue() == 0) {
            return new PageBean<>(null);
        }
        List<UserAddress> userAddressVoList = userAddressMapper.listPageByUserId(userId, PageContext.getStart(), pagesize);
        List<UserAddressDTO> userAddressDTOList = userAddressVoList.stream().map(userAddress -> {
            UserAddressDTO userAddressDTO = new UserAddressDTO();
            BeanUtils.copyProperties(userAddress, userAddressDTO);
            return userAddressDTO;
        }).collect(Collectors.toList());
        return new PageBean<>(userAddressDTOList);
    }


    /**
     * 新增地址
     *
     * @param userAddressDto
     * @throws Exception
     */
    @Override
    public void save(UserAddressDTO userAddressDto) throws ServiceException {

        if (userAddressDto.getIsDefault() == 1) {
            //移除用户默认地址
            removeDefaultAddress(userAddressDto.getUserId());
        }
        UserAddress userAddress = DozerConvert.copyProperties(userAddressDto, UserAddress.class);

        userAddress.setId(uidGenerator.getUID());
        userAddress.setCreateTime(LocalDateTime.now());
        userAddress.setUpdateTime(LocalDateTime.now());
        userAddress.setDeleted(new Byte("0"));
        userAddressMapper.insert(userAddress);
    }

    /**
     * 更新地址
     *
     * @param userAddressDTO
     */
    @Override
    public void update(UserAddressDTO userAddressDTO) throws ServiceException {
        UserAddress address = userAddressMapper.findById(userAddressDTO.getId());
        if (ObjectUtil.isEmpty(address)) {
            R.throwFail(BusinessCodeEnum.USER_ADDRESS_NOT_EXISTS);
        }

        if (userAddressDTO.getIsDefault() == 1) {
            //移除用户默认地址
            removeDefaultAddress(userAddressDTO.getUserId());
        }
        BeanUtils.copyProperties(userAddressDTO, address);
        address.setUpdateTime(LocalDateTime.now());
        userAddressMapper.update(address);
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    @Override
    public void defaultAddress(Long id, Long userId) throws ServiceException {
        UserAddress address = userAddressMapper.findById(id);
        if (ObjectUtil.isNull(address)) {
            R.throwFail(BusinessCodeEnum.USER_ADDRESS_NOT_EXISTS);
        }

        //移除用户默认地址
        removeDefaultAddress(userId);

        //设置默认地址
        address.setIsDefault(new Byte("1"));
        address.setUpdateTime(LocalDateTime.now());
        userAddressMapper.update(address);
    }

    /**
     * 查找用户默认地址
     *
     * @param userId
     * @return
     */
    @Override
    public UserAddressDTO findDefaultAddressByUserId(Long userId) throws ServiceException {
        UserAddress defaultAddress = userAddressMapper.findDefaultByUserId(userId);
        if (ObjectUtil.isNull(defaultAddress)) {
            R.throwFail(BusinessCodeEnum.USER_ADDRESS_NOT_EXISTS);
        }
        UserAddressDTO userAddressVo = DozerConvert.copyProperties(defaultAddress, UserAddressDTO.class);
        return userAddressVo;
    }

    /**
     * 移除用户默认地址
     *
     * @param userId
     */
    @Override
    public void removeDefaultAddress(Long userId) throws ServiceException {
        UserAddress defaultAddress = userAddressMapper.findDefaultByUserId(userId);
        if (ObjectUtil.isNotEmpty(defaultAddress)) {
            //默认地址修改为非默认
            defaultAddress.setIsDefault(new Byte("0"));
            defaultAddress.setUpdateTime(LocalDateTime.now());
            userAddressMapper.update(defaultAddress);
        }
    }

    /**
     * 永久删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        userAddressMapper.deleteById(id);
    }

    /**
     * 逻辑删除
     *
     * @param id
     */
    @Override
    public void deleteLogic(Long id) {
        userAddressMapper.deleteLogicById(id);
    }


}
